package cli;

import java.util.Arrays;

public class Option {
	
	private boolean exists;
	private int numOptionArgs;
	private String[] optionArgs;
	private String[] optionAliases;
	private String[] defaultOptions;
	
	public Option(int numOptionArgs, String...optionAliases) {
		this.numOptionArgs = numOptionArgs;
		this.optionAliases = optionAliases;
	}
	
	public Option(boolean exists) {
		this.exists = true;
	}
	
	public Option(String[] optionArgs) {
		this.exists = true;
		this.optionArgs = optionArgs;
	}
	
	public void extractArgs(String[] args) {
		for (int i=0;i<args.length;i++) {
			for (String alias : optionAliases) {
				if (args[i].matches(alias)) {
					if (numOptionArgs < 1) {
						this.exists = true;
					} else {
						
						
						int copyStart=0;
						int copyEnd=0;
						
						
						
						// Make sure we don't try to start copying after args.length
						if (i < args.length) {
							copyStart = i + 1;
						} else {
							copyStart = args.length;
							//copyEnd = args.length;
						}
						
						copyEnd = i + 1 + numOptionArgs;
						
						// Verify we have enough args to end copying
						/*if ((i + 1 + numOptionArgs) >= args.length) {
							copyEnd = args.length;
						} else {
							throw(new IllegalArgumentException(
									"Option " + this.optionAliases[0] + " are missing arguments"));
						}*/

						
						// Create optionArgs
						
						String[] optionArgs = Arrays.copyOfRange(args, copyStart, copyEnd);
						
						// Validate args
						this.validate(optionArgs);
						
						this.optionArgs = optionArgs; 
					}
				}
			}
		}
	}
	
	private boolean validate(String[] optionArgs) {
		
		// Validate size of args is >= numOptionArgs
		if (optionArgs.length < numOptionArgs) {
			throw(new IllegalArgumentException(
					"Option " + this.optionAliases[0] + " are missing arguments"));
		}
		
		// Check no arg is null
		for(String arg : optionArgs) {
			if (arg == null) {
				throw(new IllegalArgumentException(
						"Option " + this.optionAliases[0] + " are missing arguments"));
			}
		}
		
		return true;
	}
	
	public String[] getOptionArgs() {
		if (optionArgs == null) { 
			return defaultOptions;
		}
		else {
			return optionArgs;
		}
	}

	public void createDefaultOptions(String...defaultOptions) {
		this.defaultOptions = defaultOptions;
	}
	
	public void setDefaultOptions(String[] defaultOptions) {
		this.defaultOptions = defaultOptions;
	}

	public boolean isExists() {
		return exists;
	}
}
